#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import sys

try:
    import web
except Exception:
    print 'please install webpy first'
    sys.exit(0)

try:
    from douban.service import DoubanService
    from douban.client import OAuthClient
except ImportError:
    print 'please install douban-python'
    sys.exit(0)

try:
    from web.contrib.template import render_mako
except ImportError:
    print 'please install mako'
    sys.exit(0)

#HOST = 'http://www.douban.com'
HOST = 'http://0.0.0.0:8080'
API_KEY='035466d60107479309fd34820315d6b9'
SECRET='8b1b265afa3cddfd'

request_tokens = {}
access_tokens = {}

render = render_mako(
    directories=['templates'],
    default_filters=['decode.utf8'],
    input_encoding='utf-8',
    output_encoding='utf-8',
)

class index(object):
    def GET(self):
        commons = {'q': web.input().get('q','')}
        return render.index(**commons)

class search(object):
    def GET(self):
        q = web.input().get('q','')
        sr = []
        if q:
            service = DoubanService(api_key=API_KEY,secret=SECRET)
            feed = service.SearchMusic(q.encode('utf-8'))
            for result in feed.entry:
                sr.append(result)
                print "\n\nMMMM\n\n", result
        return render.srp(q= web.input().get('q',''), sr=sr)

class collection(object):
    def GET(self):
        sid = web.input().get('sid','')
        if not sid:
            return 'no sid'
        
        client = OAuthClient(key=API_KEY, secret=SECRET)
        cookies = web.cookies()
        access_key = cookies.get('access_key')
        access_secret = access_tokens.get(access_key)
        if not access_key or not access_secret:
            request_key = web.input().get('oauth_token','')
            request_secret = request_tokens.get(request_key)
            if request_key and request_secret:
                try:
                    res = client.get_access_token(request_key, request_secret)
                except Exception:
                    access_token = None
                    return '获取用户授权失败'
                access_key, access_secret, foo = res
                if access_key and access_secret:
                    # store user access key in cookie, 
                    # not accessable by other people
                    web.setcookie('access_key', access_key)
                    access_tokens[access_key] = access_secret
            else:
                client = OAuthClient(key=API_KEY, secret=SECRET)
                key, secret = client.get_request_token()
                if key and secret:
                    request_tokens[key] = secret
                    url = client.get_authorization_url(key, secret, callback=HOST+'/collection?sid='+sid)
                    web.tempredirect(url)
                    return
                else:
                    return '获取 Request Token 失败'

        service = DoubanService(api_key=API_KEY, secret=SECRET)
        movie = service.GetMovie(sid)
        if access_key and access_secret:
            if service.ProgrammaticLogin(access_key, access_secret):
                try:
                    entry = service.AddCollection('wish', movie, tag=['test'])
                    if entry:
                        text = 'Added to your favorites'
                    else:
                        text = 'Failed to add to favorites'
                except Exception:
                    text = 'Authorization failure'
                    del access_tokens[access_key]
                    web.setcookie('access_key', '', 0)
        else:
            text = 'Can not add favorites, maybe because you did not authorize this application to access your data in Douban'
        return render.coll(q= web.input().get('q',''), movie=movie, text=text)

urls = (
    '/', 'index',
    '/search', 'search',
    '/collection', 'collection',
)

app = web.application(urls, globals())

if __name__ == '__main__':
    app.run()
